package com.distributeredis.redis_springboot.springreflect.utils;
import com.distributeredis.redis_springboot.springreflect.demotest.vo.PeopleDept;
import com.distributeredis.redis_springboot.springreflect.demotest.vo.PeopleFamary;

import java.lang.reflect.Field;
import java.util.List;

public class ReflectUtils {
    // 通用模式
    public static void ObjectCommonFieldTrim(Object obj) throws IllegalAccessException {
        Class<?> aClass = obj.getClass();
        Field[] declaredFields = aClass.getDeclaredFields();
        for (Field declaredField : declaredFields) {
            Class<?> type = declaredField.getType();
            if(type.equals(String.class)) {
                declaredField.setAccessible(true);
                String value = (String) declaredField.get(obj);
                String trimValue = value.trim();
                declaredField.set(obj,trimValue);
            }
        }
    }
    // 针对单个
    public static void ObjectFieldTrim(Object obj) throws IllegalAccessException {
        Class<?> aClass = obj.getClass();
        Field[] declaredFields = aClass.getDeclaredFields();
        for (Field field : declaredFields) {
            Class<?> type = field.getType();
            // 如果参数是字符串类型
            filterTrimValue(obj, field, type);
            // 如果参数包含对象类型
            if(type.equals(PeopleFamary.class)) {
                field.setAccessible(true);
                PeopleFamary peopleFamary = (PeopleFamary) field.get(obj);
                Class<? extends PeopleFamary> aClass1 = peopleFamary.getClass();
                Field[] fields = aClass1.getDeclaredFields();
                for (Field field1 : fields) {
                    Class<?> type1 = field1.getType();
                    filterTrimValue(peopleFamary,field1,type1);
                }
            }
            // 如果参数包含集合类型
            if(type.equals(List.class)) {
                field.setAccessible(true);
                List<PeopleDept> peopleDepts = (List<PeopleDept>) field.get(obj);
                for (PeopleDept peopleDept : peopleDepts) {
                    Class deptClass = peopleDept.getClass();
                    Field[] classDeclaredFields = deptClass.getDeclaredFields();
                    for (Field declaredField : classDeclaredFields) {
                        Class<?> fieldType = declaredField.getType();
                        filterTrimValue(peopleDept,declaredField,fieldType);
                    }
                }
            }
        }
    }

    private static void filterTrimValue(Object obj, Field field, Class<?> type) throws IllegalAccessException {
        if(type.equals(String.class)) {
            field.setAccessible(true);
            String value = (String) field.get(obj);
            String trimValue = value.trim();
            field.set(obj,trimValue);
        }
    }
}
